/**
 * 淘金矿场公用JS
 * @author kevinE kevin-e-e@foxmail.com
 * @version 1.1 2021-9-25 10:17:48
 */

// 后端接口appKey
const APPKEY = "5ded368547b86b331";
// 云片appId
const YP_APPId = "80fe987ccea24085bc07bd8a00587d42";
// 后端请求域
let ua = navigator.userAgent;
let DOMAIN = '';
if (~ua.indexOf('iPhone')) DOMAIN = "http://api.jztmall.cn:99";
else DOMAIN = "http://cat.jztmall.cn:99";
// 二维码短链
const SHORT_URL = "http://cat.jztmall.cn:99/qr.html/";
// cookie前缀
const PREFIX = 'cat';
// 登录页面
const LOGIN_PAGE = 'login.html';
// 接口地址
const API_PATH = {
	// 检查版本信息
	CHECK_VERSION: DOMAIN + "/home/index/getVersion",
	// 短信验证码接口url
	SMS_CODE: DOMAIN + "/home/index/sendSms",
	// 注册接口路径
	REGISTER: DOMAIN + "/home/index/register",
	// 登录接口路径
	LOGIN: DOMAIN + "/home/index/login",
	// 找回/重置密码
	RESET_PWD: DOMAIN + "/home/index/resetPassword",
	// 绑定支付宝账号
	BIND_ALIPAY: DOMAIN + "/home/user/realAuth",
	// 获取用户信息接口url
	USER_INFO: DOMAIN + "/home/user/getUserInfo",
	// 直推好友
	DIRECT_FRIEND: DOMAIN + "/home/user/getDirectFriend",
	// 间推好友
	INDIRECT_FRIEND: DOMAIN + "/home/user/getIndirectFriend",
	// 团队好友(三代及以后)
	GROUP_FRIEND: DOMAIN + "/home/user/getTenGenerationsFriend",
	// 提现
	WITHDRAWAL: DOMAIN + "/home/user/withdrawal",
	// 零钱记录
	BALANCE_RECORD: DOMAIN + "/home/user/balanceDetailList",
	// 获取转盘奖励列表
	TURN_LIST: "/home/index/turnindex",
	// 使用转盘抽奖
	DO_TURN: "/home/turn/doTurn",
	// 领取收益
	RECEIVE_MONEY: DOMAIN + "/home/user/getBonusMoney",
	// 领取 MMT 
	RECEIVE_MMT: DOMAIN + "/home/user/getMmt",
	// 绑定微信账户 wx_user：微信号 wx_nickname：真实姓名 wx_img：收款码
	BIND_WECHAT: DOMAIN + "/home/user/bindWx",
	//游戏等级领奖
	GAME_UPGRADE: "/home/user/gameUpgradeGetGoldCoin",
	// 获取 MMT, 铜板 详情; 参数type, 1:MMT, 2:铜板
	GET_RECORD_LIST: DOMAIN + "/home/user/getRecordList",
	// 猫咪升级
	UPDATE_CAT_LV: DOMAIN + "/home/user/upgrade",
	//公告
	NEWS: DOMAIN + "/home/user/news",
}
//游戏等级列表
const game_level_list_url = "/home/user/getGameLevelList";
// 游戏余额记录
const game_money_record_url = "/home/user/gameMoneyDetailList";

// 2021-02-26 kevin
// 领取 游戏等级每日奖励
const get_reward_everyday = "/home/user/getTurnRoll";

// 2021-3-4 kevin
const get_popularize_welfare = "/home/user/welfare";
const get_owner_support = "/home/user/support";

// 2021-5-19 获取优益互娱/爱乐趣游戏的GUID
const get_yyhy_guid_url = "/home/game/getGameUid";
// 2021-5-19 通知后端更新联盟豆发放记录
const update_charge_logs_url = "/home/game/getChargeLogs";
// 2021-6-13 兔兔币分页/home/user/giveFriends
const rabbit_coin_record = "/home/user/getGoldCoinList";
//2021-6-13 赠送兔兔币
const give_rabbit_coin = "/home/user/giveFriends";
//2021-6-13 排行榜列表
const rank_list = "/home/user/dividendRanking";
//2021-6-13 充值记录
const pay_record = "/home/user/getChargeLog";
//2021-6-13 分红兔
const fenhong_rabbit = "/home/index/getData";
//2021-6-22 提交申请 id
const submit_signUp = "/home/user/signUp";
//2021-6-22 兑换成功记录  参数：id
const reward_log = "/home/index/reward_log";
//2021-6-23 佣金排行榜  参数：page
const commission_log = "/home/index/commission_log";
//2021-6-23 保存收货地址  参数：name,mobile,province,city,area,address
const save_address = "/home/user/address";
//2021-6-23 获取转盘券
const turn_getTurnTickt = "/home/turn/getTurnTickt";
//2021-7-20 获取转盘券
const turn_getTurnRoll = "/home/user/getTurnRoll";
//2021-6-24 获取报名状态和报名人数
const get_signInfo = "/home/user/signInfo";
//2021-6-24 获取转盘券状态
const get_turn_status = "/home/user/getTurnStatus";


// 判断用户是否登录或者登录是否有效
function checkLogin() {
	var token = getCookie("token");
	if (!token) location.href = LOGIN_PAGE;
}

/**
 * 设置cookie
 * @param {String} key 键名
 * @param {String} value 键值
 * @param {Number} expire 有效期(秒)
 */
function setCookie(key, value, expire = 0) {
	var now = new Date();
	now.setDate(now.getTime() + expire);
	document.cookie = key + "=" + value + "; path=/; expires=" + now.toDateString();
}
/**
 * 读取cookie
 * @param {String} key 键名
 */
function getCookie(key) {
	var arr1 = document.cookie.split("; ");
	for (var i = 0; i < arr1.length; i++) {
		var arr2 = arr1[i].split("=");
		if (arr2[0] == key) {
			return decodeURI(arr2[1]);
		}
	}
	return '';
}
/**
 * [removeCookie 移除cookie]
 */
function removeCookie(key) {
	setCookie(key, "", -1); // 把cookie设置为过期
	localStorage.removeItem(key);
}
//清除所有cookie函数
function clearAllCookie() {
	var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
	console.log(keys);
	if (keys) {
		for (let i = 0; i < keys.length; i++) {
			setCookie(keys[i], null, -1);
		}
	}
}

// 提示
function openTips(str, n = 2000, f = 25) {
	let t = new Date();
	let d = document.createElement("div");
	d.className = "tips";
	d.innerHTML = "<span>" + str + "</span>";
	document.body.appendChild(d);
	setTimeout(() => {
		let o = 0.95;
		let s = setInterval(() => {
			o -= 0.05;
			if (o < 0) {
				clearInterval(s);
				document.body.removeChild(d);
			} else {
				d.style.opacity = o;
			}
		}, f);
	}, n);
}

// 复制文本内容
function copy(str) {
	var oInput = document.createElement("input");
	oInput.value = str;
	document.body.appendChild(oInput);
	oInput.select(); // 选择对象
	var ec = document.execCommand("Copy"); // 执行浏览器复制命令
	oInput.style.display = "none";
	return ec;
}

/**
 * 获取用户信息
 * @param {Function} cb 回调函数
 */
function getUserInfo(cb) {
	let token = getCookie("token");
	let userid = getCookie("userid");
	if (!token) {
		openTips("暂未登录，请先登录");
		setTimeout(function() {
			location.replace(LOGIN_PAGE);
		}, 1000);
		return false;
	}
	ajax({
		method: 'GET',
		url: API_PATH.USER_INFO,
		header: {
			'Content-type': 'application/x-www-form-urlencoded',
			'TC-Token': token,
			'TC-Id': userid,
			'appKey': APPKEY
		},
		success: (res) => {
			if (res.code != 1) {
				openTips("登录失效，请重新登录");
				setTimeout(function() {
					location.replace(LOGIN_PAGE);
				}, 1000);
				return;
			}
			// 存储必要的用户信息
			setInfo(res.data);
			// debugger
			cb && cb(res.data);
		}
	});

	function setInfo(data) {
		var dt = 365 * 24 * 60 * 60;
		setCookie("direct", data.Direct, dt);
		setCookie("yellow_diamond", data.dragon_coins, dt);
		setCookie("red_diamond", data.dragon_jin, dt);
		setCookie("user_money", data.money, dt);
		setCookie("is_check", data.is_check, dt);
		setCookie("level", data.level, dt);
		setCookie("invite_code", data.invite_code, dt);
		setCookie("mobile", data.mobile, dt);
		setCookie("p_mobile", data.p_mobile, dt);
		setCookie("turn_num", data.turn_num, dt);
		setCookie("type", data.type, dt);
		setCookie("coins", data.bonus_card, dt);
		setCookie("alipay_name", data.alipay_name, dt);
		setCookie("alipay_account", data.alipay_account, dt);
		setCookie("wx_img", data.wx_img, dt);
		setCookie("nickname", data.nickname, dt);
	}
}

function goBack() {
	history.back();
}

function navgateTo(str) {
	if (str) location.href = str;
}

// 存储数据到localStorage 支持对象存储
function setItem(k, v) {
	localStorage.setItem(k, JSON.stringify(v));
}
// 读取local storage 数据
function getItem(k) {
	return JSON.parse(localStorage.getItem(k));
}

// 获取DOM节点
function $(str) {
	if (str.indexOf('#') === 0) {
		return document.getElementById(str.substr(1));
	} else
	if (str.indexOf('.') === 0) {
		return document.getElementsByClassName(str.substr(1));
	} else {
		return document.getElementsByTagName(str);
	}
}

// 2021-5-19 kevin 获取设备类型
function getClientType() {
	let ua = navigator.userAgent.toLowerCase();
	if (ua.indexOf("iphone") > 0 || ua.indexOf("ipad") > 0) {
		return "iphone";
	} else if (ua.indexOf("android") > 0) {
		return "android";
	} else if (ua.indexOf("windows") > 0) {
		return "windows";
	} else {
		return "other";
	}
}

// 获取URL参数 2021-5-20
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = window.location.search.substr(1).match(reg); //匹配目标参数
	if (r != null) return unescape(r[2]);
	return null; //返回参数值
}

/**
 * 获取JSON配置文件
 * by kevinE 2021-9-25 15:04:18
 * @param {URL} url 请求文件地址
 * @param {Function} cb 成功回调
 * @return {JSON} json json对象
 */
async function getConfig(url, cb) {
	const res = await fetch(url);
	const json = await res.json();
	cb && cb(json);
	return json;
}

/**
 * 获取设备信息
 * by kevinE 2021-12-2 15:02:27
 * @param {String} key 属性名称,不传返回所有
 * @return {String} 设备属性值
 */
function deviceInfo(key) {
	let nav = navigator || window.navigator;
	let scr = screen || window.screen;
	let info = {
		innerWidth: innerWidth,
		innerHeight: innerHeight,
		outerWidth: outerWidth,
		outerHeight: outerHeight,
		screenWidth: scr.width,
		screenHeight: scr.height,
		screenLeft: screenLeft,
		screenTop: screenTop,
		screenAngle: scr.orientation.angle,
		deviceMemory: nav.deviceMemory,
		hardwareConcurrency: nav.hardwareConcurrency,
		maxTouchPoints: nav.maxTouchPoints,
		platform: nav.platform,
		downlink: nav.connection.downlink,
		effectiveType: nav.connection.effectiveType,
		netType: nav.connection.type || 'line',
		onLine: nav.onLine,
		devicePixelRatio: nav.devicePixelRatio
	}
	return key ? info[key] : info;
}

/**
 * 数字对象拓展 数字缩短长度
 * @author kevinE kevin-e-e@foxmail.com
 * @version v1.0 2021-11-5 09:33:25
 * @param {Number} prec 保留小数位
 * @param {Number} type 显示模式 1中文,2英文
 */
Number.prototype.format = function(type = 1) {
	let prec = 2;
	let _this = parseFloat(this);
	if (_this > 100000000) {
		if (type === 1) {
			if (_this > 10000000000) {
				return (_this / 100000000).toFixed(1) + '亿';
			} else return (_this / 100000000).toFixed(prec) + '亿';
		} else return (_this / 100000000).toFixed(prec) + 'E';
	}
	if (_this > 10000) {
		if (type === 1) {
			if (_this > 1000000) return (_this / 10000).toFixed(1) + '万';
			else return (_this / 10000).toFixed(prec) + '万';
		} else return (_this / 10000).toFixed(prec) + 'W';
	} else return parseFloat(_this).toFixed(prec);
}

/**
 * 日期对象拓展 日期格式化
 * @author kevinE kevin-e-e@foxmail.com
 * @version v1.0 2021-9-25 14:39:43
 * @param {String} format 格式字符串，支持大写字母Y M D H I S C，其他字符原样输出
 * @param {String} date [日期字符]，默认使用当前时间
 */
Date.prototype.format = function(format, date) {
	const fm = ['Y', 'M', 'D', 'H', 'I', 'S', 'C'];
	let Y, M, D, H, I, S, C, d, str = '';
	if (date) d = new Date(date);
	else d = new Date();
	let _Y = d.getFullYear();
	let _M = d.getMonth() + 1;
	_M = _M < 10 ? '0' + _M : _M;
	let _D = d.getDate();
	_D = _D < 10 ? '0' + _D : _D;
	let _H = d.getHours();
	_H = _H < 10 ? '0' + _H : _H;
	let _I = d.getMinutes();
	_I = _I < 10 ? '0' + _I : _I;
	let _S = d.getSeconds();
	_S = _S < 10 ? '0' + _S : _S;
	let _C = d.getMilliseconds();
	_C = _C < 100 ? _C < 10 ? '00' + _C : '0' + _C : _C;
	for (var i = 0; i < format.length; i++) {
		let fi = format[i];
		if (fm.indexOf(fi) >= 0) str += eval('_' + fi);
		else str += format[i];
	}
	return str;
}

/**
 * 发送ajax请求
 * @author kevinE kevin-e-e@foxmail.com
 * @version v1.0 2021-9-25 15:00:30
 * @param {JSON} cfg xhr配置
 * @param {URLString} cfg.url 请求路径
 * @param {String} cfg.method 请求方式[GET, POST]
 * @param {JSON} cfg.header 请求头
 * @param {JSON} cfg.data 请求参数
 * @param {Function} cfg.success 成功回调
 * @param {Boolean} cfg.isAsync 是否异步
 * @param {Function} cfg.error 错误回调
 */
function ajax({
	url,
	method,
	header,
	data,
	success,
	isAsync,
	error
}) {
	ver = getCookie('xhr.ver') || new Date().format('YMDHIS');
	method = method || 'GET';
	isAsync = isAsync === undefined ? true : isAsync;
	let _data = '';
	let i = 0;
	for (let k in data) {
		_data += '&' + k + '=' + data[k];
		i++;
	}
	let xhr = new XMLHttpRequest();
	if (method === 'GET')
		url = url + '?v=' + ver + _data;
	else url = url + '?v=' + ver;
	xhr.open(method, url, isAsync);
	if (method === 'POST')
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	if (header) {
		for (let key in header) {
			xhr.setRequestHeader(key, header[key]);
		}
	}
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4 && xhr.status === 200) {
			let res = JSON.parse(xhr.responseText);
			success && success(res);
		} else if (xhr.readyState == 4 && xhr.status !== 200) {
			error && error(xhr);
		}
	}
	xhr.send(_data);
}

/**
 * 缓存控制器 静态HTML版本管理 不能真正清除缓存文件
 * 工作原理是通过控制版本号 绕过缓存机制实现强制刷新页面
 * @author kevinE kevin-e-e@foxmail.com
 * @version v1.0 2021-9-25 14:43:41
 * @example 在需要做版本控制的页面执行该函数 使用cleanCache函数清除缓存更新版本
 */
function ctrlCache() {
	// 缓存版本键名
	let vk = PREFIX + '-ver';
	// 缓存版本[数字]
	let vv = getItem(vk) || new Date().format('YMDHIS');
	// 缓存文件键名
	let ck = PREFIX + '-cache-' + vv;
	// 缓存文件[数组]
	let cf = getItem(ck) || [];
	// 当前页面路径
	let hf = location.origin + location.pathname;
	// 当前页面不在缓存中
	if (cf.indexOf(hf) < 0) {
		// 将当前路径存入缓存
		console.log(hf)
		cf.push(hf);
		// 添加版本号后重新加载
		let _hf = hf + '?v=' + vv;
		// 存储缓存版本
		setItem(vk, vv);
		// 存储缓存文件名
		setItem(ck, cf);
		location.replace(_hf);
		return false;
	}
}
// 清空缓存[强制刷新]
function cleanCache() {
	// 缓存版本键名
	let vk = PREFIX + '-ver';
	// 获取已有版本信息
	let _vv = getItem(vk);
	// 缓存文件键名
	let ck = PREFIX + '-cache-' + _vv;
	// 清除已有缓存文件
	localStorage.removeItem(ck);
	// 缓存新版本号
	let vv = new Date().format('YMDHIS');
	// 存储新的缓存版本
	setItem(vk, vv);
	// 查询最新版本 判断是否更新成功
	let nv = getItem(vk);
	// 返回操作结果
	return vv == nv;
}

// function a() {
// 	let fileName = 'share'
// 	var bitmap = new plus.nativeObj.Bitmap('share')
// 	bitmap.loadBase64Data(this.posterUrl, function(e) {
// 		console.log('加载Base64图片数据成功')
// 		// 如果传入文件名称为空，则直接设置APP名称为文件名称  
// 		if (fileName === undefined) {
// 			fileName = plus.runtime.name
// 		}

// 		fileName = fileName + +(new Date) + '.png'

// 		bitmap.save('_doc/' + fileName, {}, function(i) {
// 			console.log('保存图片成功：' + JSON.stringify(i))
// 			plus.gallery.save(i.target, function(e) {
// 				console.log('保存图片成功：' + JSON.stringify(e))
// 				Toast(`图片保存到:${e.file}`)
// 			}, function() {
// 				Toast(`图片保存失败`)
// 			})
// 		}, function(e) {
// 			console.log('保存图片失败：' + JSON.stringify(e))
// 			Toast(`图片保存失败`)
// 		})
// 	}, function(e) {
// 		console.log('加载Base64图片数据失败：' + JSON.stringify(e))
// 		Toast(`图片保存失败`)
// 	})
// }

// document.body.addEventListener('touchstart', function() {});
